package com.baichen.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

public class NettyClientDemo {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024)) // 处理分隔符
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(new SimpleChannelInboundHandler<String>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                        System.out.println("Received from server: " + s);
                                    }
                                });
                    }
                });
        ChannelFuture connect = bootstrap.connect("localhost", 8888);
        connect.addListener(f -> {
            if (f.isSuccess()) {
                System.out.println("Netty client connected to server successfully on port 8888");
                EventLoop eventExecutors = connect.channel().eventLoop();
                eventExecutors.scheduleAtFixedRate(() -> {
                    try {
                        String message = "Hello,\n Netty Server!";
                        connect.channel().writeAndFlush(message + "\n");
                        System.out.println("Sent to server: " + message);
                    } catch (Exception e) {
                        System.err.println("Error sending message: " + e.getMessage());
                    }
                }, 0, 2, TimeUnit.SECONDS);
            } else {
                System.err.println("Failed to connect to Netty server: " + f.cause());
            }
        });
    }
}
